local oo = require("SharedLibs.BaseLib");
local co = require("SharedLibs.CoroLib");


AsyncOp = require("SharedLibs.AsyncOp");
CU = require("SharedLibs.CoUtils");

--[[
	类似普通的while, 区别是:
	1. 这里的条件是通过Condition对象来实现的.
	2. 条件成立后执行的是一个异步操作(AsyncOp)
]]
WhileOp = oo.Class();
WhileOp.name = "WhileOp";
oo.ClassExtends(WhileOp, AsyncOp);

--[[
	op可以是任意能被转换成AsyncOp的对象, 必须支持Reset()
	condition是一个Condition对象
	
	forceStop 为true, 那么当condition为false时,Op会被立刻停止, 整个WhileOp结束
	forceStop 为false, 那么当condition为false时, Op不会被立刻停止, 而是等待其执行
	完毕后, 整个WhileOp才结束
]]
function co.While(condition, op, forceStop)
	local op = oo.New(WhileOp, condition, op, forceStop);
	return co.yield(op);
end

function co.NewWhile(condition, op, forceStop)
	return oo.New(WhileOp, condition, op, forceStop);
end

function WhileOp.prototype:constructor(condition, op, forceStop)
	WhileOp._ss.prototype.constructor(self)

	self._condition = condition;
	self._op = CU.ToOp(op);
	self._forceStop = forceStop;	
end

function WhileOp.prototype:_onStart()
	if not self._condition:GetValue() then 
		self:_doStop(true);
	else
		if self._forceStop then
			local handler = function(val) 
				if not val then
					self:_doStop(true);
				end
			end;
			self._condition.__handler = handler;
			self._condition:On(handler);
		end
		
		local onOpEnd = nil;
		onOpEnd = function() 
			if not self._condition:GetValue() then 
				self:_doStop(true);
			else
				self._op:Reset();
				self._op:Start(onOpEnd, self, true);
			end
		end
		
		self._op:Start(onOpEnd, self, true);
	end	
end

function WhileOp.prototype:_onStop()
	self._op:Stop();
	
	local condition = self._condition;
	if self._forceStop then
		condition:Off(condition.__handler);
		condition.__handler = nil;
	end	
end

function WhileOp.prototype:_onReset()
	self._op:Reset();
end

function WhileOp.prototype:_onPause()
	if self._op then	
		self._op:Pause();
	end	
end

function WhileOp.prototype:_onResume()
	if self._op then	
		self._op:Resume();
	end
end

return WhileOp;


